#-*- coding:utf-8 -*-
"""assignShaders by Ozgur Yilmaz and Begum Baskan (c) 2013

Description :
-------------
Assigns the shaders according to the current render layer and the quick
selection sets in the current scene, the quick selection sets name should
start with the renderLayer name and should include at least one shading
group name

Ex : defaultRenderLayer_renderSG_animSG

Mainly used to switch shaders in render layers and to switch from
animation shaders to render shaders

Version History
---------------
0.1.0:
- the initial version.
"""

__version__ = "0.1.0"

import pymel.core as pm


class Editor(object):
    @classmethod
    def UI(cls):
        wWidth = 300
        wHeight = 380

        if pm.window("assignShader_Window", q=True, ex=True):
            pm.deleteUI("assignShader_Window", wnd=True)

        assignShader_Window = pm.window('assignShader_Window', wh=(wWidth, wHeight),
                                        t=("Assign Shader " + __version__))

        #create a tab layout to hold create and edit functionalities separate

        pm.showWindow(assignShader_Window)
        #pm.window(assignShader_Window, edit=True, wh=(wWidth,wHeight))

def assign_shaders(shaderIndex):
    objSet = pm.ls(type="objectSet")
    for sets in objSet:
        if sets.hasAttr('shaderList'):
            renderLayer = pm.editRenderLayerGlobals(currentRenderLayer=True, q=True)
            setBaseName = sets.split(':')[-1]
            if setBaseName == renderLayer:
                conn = sets.shaderList[shaderIndex].connection()
                sets.shaderList[shaderIndex].listConnection()
                shader = conn[0]

                print ("setName: %s\nshader: %s" % (sets, shader))
                if len(shader) > 0:
                    shader.sets(fe=True)
                    sets.sets(q=True)


class Material(object):
    def __init__(self):
        self._stringSet = None
        self._passList = None
        self._shaderList = None

    def create_material_set(self, objList, passList, shaderList):
        listCount = min(len(passList), len(shaderList))
        setName = passList[0]
        for i in range(0, listCount):
            setName = "%s_%s" % (setName, shaderList[i])
        nodeSet = pm.createNode('objectSet', n=setName)
        pm.sets(nodeSet, fe=objList)
        self._stringSet = nodeSet
        self.create_attribute
        self.passList
        self.shaderList

    def create_attribute(self):
        stringSet = self._stringSet
        if stringSet.hasAttr('shaderList'):
            pass
        else:
            stringSet.addAttr('shaderList', at='message', sn='sl', m=True)
        if stringSet.hasAttr('passList'):
            stringSet.addAttr('passList', dt="string", sn='pl', m=True)

    @property
    def passList(self):
        return self._passList

    @passList.setter
    def passList(self, passList):
        self._passList = passList
        stringSet = self._stringSet
        for i in range(0, len(passList)):
            stringSet.passList[i].set(passList, type="string")

    @property
    def shaderList(self):
        return self._shaderList

    @shaderList.setter
    def shaderList(self, shaderList):
        self._shaderList = shaderList
        for i in range(0, len(shaderList)):
            shaderList[i].message.connectAttr((self._stringSet + ".shaderList[%f]" % i), f=True)


class Set(object):
    @classmethod
    def get_sets(cls):
        allSets = pm.ls(type="objectSet")
        newSetList = []
        for stringSet in allSets:
            if Set.has_attributes(stringSet) == 3:
                newSetList.append(stringSet)
        return newSetList

    @classmethod
    def has_attributes(cls, stringSet):
        shaderListExists = stringSet.hasAttr('shaderList')
        passListExists = stringSet.hasAttr('passList')
        returnStat = 0

        if shaderListExists and passListExists:
            returnStat = 3
        elif shaderListExists and (not passListExists):
            returnStat = 1
        elif (not shaderListExists) and passListExists:
            returnStat = 2
        return returnStat


class Old(object):
    @classmethod
    def convert_from_old_setup(cls):
        selList = pm.ls(sl=1)
        for sets in selList:
            if sets.hasAttr('shaderList'):
                pass
            else:
                sets.addAttr('shaderList', at='message', sn='sl', m=True)
            if sets.hasAttr('passList'):
                pass
            else:
                sets.addAttr('passList', dt="string", sn='pl', m=True)

            token = sets.split('_')
            for i in range(1, len(token)):
                shadingGroup = sets[i]
                shadingGroup.message.connectAttr((sets + '.sl[%f]' % (i - 1)))
                sets[0].setAttr((sets + '.pl[%f]' % (i - 1)))
            sets.rename(sets + '_converted')

    @classmethod
    def assign_shaders_old(cls, shaderIndex):
        selSet = pm.ls(type="objectSet")

        renderLayer = pm.editRenderLayerGlobals(q=True, currentRenderLayer=True)
        for i in range(0, len(selSet)):
            setBaseName = selSet[i].split(':')[-1]
            if setBaseName == renderLayer:
                token = setBaseName.split('_')
                if shaderIndex >= len(token):
                    pm.warning("there is no such shader with that index, setting to last one!")
                    shaderIndex = len(token) - 1
                shader = pm.ls(setBaseName[shaderIndex], r=1)
                pm.sets(fe=shader[0])
                selSet[i].sets(q=True)